module AppiumRspecSetup
  class SetupAndroid
    def self.setup_android!
      AppiumRspecSetup::Gemfile.configure_gemfile_and_bundle!
      AppiumRspecSetup::Rspec.initialize_rspec

      puts 'What is the name of the app?'
      app_name = gets.chomp

      puts 'What is the name of the platform?'
      platform_name = gets.chomp

      File.open('app_config.yml', 'w') do |file|
        file.write %Q{
rspec:
  app_name: #{app_name}
  platform_name: #{platform_name}
               }
      end

      spec_helper = File.readlines('spec/spec_helper.rb')

      require_hash = {
        'appium_lib' => "require 'appium_lib'",
        'pry' => "require 'pry'",
        'yaml' => "require 'yaml'"
      }

      require_hash.each do |substring_key, line_for_spec_helper|
        spec_helper.insert(-1, line_for_spec_helper) unless spec_helper.any? do |line|
          line.include? substring_key
        end
      end

      yaml_definitions_hash = {
        'APP_CONFIG' => "::APP_CONFIG = YAML.load(File.read('./app_config.yml'))",
        'APP_NAME' => "::APP_NAME = APP_CONFIG['rspec']['app_name']",
        'PLATFORM_NAME' => "::PLATFORM_NAME = APP_CONFIG['rspec']['platform_name']",
        'APP_PATH' => "::APP_PATH = \"../\#{APP_NAME}/app/build/outputs/apk/app-debug.apk\""
      }

      yaml_definitions_hash.each do |substring_key, line_for_spec_helper|
        spec_helper.insert(-2, line_for_spec_helper) unless spec_helper.any? do |line|
          line.include? substring_key
        end
      end

      unless spec_helper.any? { |line| line.include? 'def desired_caps' }
        spec_helper.insert(-2, %Q{
    def desired_caps
      {
        caps: {
          :'appium-version' => '1.0',
          platformName: PLATFORM_NAME,
          deviceName: 'DJVis',
          app: APP_PATH,
          name: APP_NAME
        },
        appium_lib: {
        wait: 60
        }
      }
    end
    } )
      end

      File.open('spec/spec_helper.rb', 'w') do |file|
        file.puts spec_helper
      end
    end
  end
end